#include "viml/debugger_cli.h"
#include <algorithm>
#include <cctype>

namespace viml {

CommandCompleter::CommandCompleter() {
    initialize();
}

void CommandCompleter::initialize() {
    // 基本调试命令
    add_command("help", {"show", "usage"});
    add_command("quit", {"exit"});
    add_command("continue", {"run", "c"});
    add_command("step", {"next", "n"});
    add_command("stepinto", {"si"});
    add_command("stepover", {"so"});
    add_command("stepout", {"finish", "return"});
    add_command("breakpoint", {"bp", "b"});
    add_command("break", {"b"});
    add_command("clear", {"delete", "del"});
    add_command("delete", {"remove", "del"});
    add_command("list", {"info", "show"});
    add_command("info", {"show"});
    add_command("backtrace", {"bt", "where"});
    add_command("where", {"bt", "backtrace"});
    add_command("print", {"p", "display"});
    add_command("locals", {"l", "var"});
    add_command("globals", {"g", "global"});
    add_command("frame", {"f", "select"});
    add_command("up", {"u"});
    add_command("down", {"d"});
    add_command("disassemble", {"disasm", "x"});
    add_command("run", {"start", "execute"});
    add_command("finish", {"return"});
    add_command("condition", {"cond"});
    add_command("ignore", {"ign"});
    add_command("enable", {"e"});
    add_command("disable", {"d"});
}

void CommandCompleter::add_command(const std::string& name, const std::vector<std::string>& args) {
    commands.push_back(name);
    command_args[name] = args;

    // 添加所有参数作为单独的补全选项
    for (const auto& arg : args) {
        commands.push_back(arg);
    }
}

std::vector<std::string> CommandCompleter::complete(const std::string& partial, size_t cursor_pos) {
    std::vector<std::string> matches;

    // 只在命令开始时进行补全（简单实现）
    if (partial.empty() || cursor_pos == 0 || !std::isalpha(partial[0])) {
        return matches;
    }

    for (const auto& cmd : commands) {
        if (cmd.length() >= partial.length()) {
            if (cmd.substr(0, partial.length()) == partial) {
                matches.push_back(cmd);
            }
        }
    }

    // 移除重复项并排序
    std::sort(matches.begin(), matches.end());
    matches.erase(std::unique(matches.begin(), matches.end()), matches.end());

    return matches;
}

} // namespace viml